/*
 * File:    Guid.java
 * Created: 06-Nov-2007
 *
 * by Kenji Hollis <kenji@bitgatesoftware.com>
 * Released under the Creative Commons License version 2.5
 */

package com.bitgate.util.guid;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.SecureRandom;
import java.util.Random;

import com.bitgate.util.encoder.MD5;

/**
 * Creates a GUID class that can be used to generate a GUID on the fly.  The GUID is based on the IP address of your
 * local system (by name) and the system generates the GUID based on a random number using the <code>SecureRandom</code>
 * class.  Since the <code>SecureRandom</code> class is used, it is implied that the random number generated here
 * will be &quot;more random&quot; than otherwise created.  Whether or not this is actually the case remains to be
 * tested in your code.
 * 
 * @author Kenji Hollis &lt;kenji@bitgatesoftware.com&gt;
 * @since 0.1
 */
public class Guid
{
    private static String s_id;
    private final static Random myRand;
    private final static SecureRandom mySecureRand;

    /**
     * Public static constructor.
     */
    static {
        mySecureRand = new SecureRandom();
		long secureInitializer = mySecureRand.nextLong();
		myRand = new Random(secureInitializer);
	
		try {
		    s_id = InetAddress.getLocalHost().toString();
		} catch(UnknownHostException e) {
		    s_id = "127.0.0.1";
		}
    }

    /**
     * Generates a random GUID.
     *
     * @return <code>static String</code> containing a generic GUID, in caps.
     */
    public static String getGuid()
    {
		long time = System.currentTimeMillis();
		long rand = 0;
		StringBuffer sBuffer = new StringBuffer();
	
		rand = myRand.nextLong();
	
		sBuffer.append(s_id);
		sBuffer.append(":");
		sBuffer.append(time);
		sBuffer.append(":");
		sBuffer.append(rand);
	
		String raw = MD5.md5(sBuffer.toString()).toUpperCase();
		StringBuffer out = new StringBuffer();
	
		out.append(raw.substring(0, 8));
		out.append("-");
		out.append(raw.substring(8, 12));
		out.append("-");
		out.append(raw.substring(12, 16));
		out.append("-");
		out.append(raw.substring(16, 20));
		out.append("-");
		out.append(raw.substring(20));
	
		raw = null;
		sBuffer = null;
	
		return out.toString();
    }
}
